package com.pingba.util.helper;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.pingba.entity.msg.MsgApply;
import com.pingba.entity.msg.MsgSend;
import com.pingba.entity.msg.MsgSubscribe;
import com.pingba.entity.msg.MsgType;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/10/25 0025.
 */
public class JsonHelp {

    private static Logger logger = Logger.getLogger(JsonHelp.class);
    private static Gson sGson = new Gson();

    public static String jsonFromObject(Object object) {
        return sGson.toJson(object);
    }

    public static <T> T objectFromJson(String json, Class<T> clz) {
        T object =  null;
        try {
            object = sGson.fromJson(json, clz);
        } catch (JsonSyntaxException e) {
            logger.error("Json Cast error, from " + json + " to " + clz.toString(),  e.getCause());
        }
        return object;
    }

    public static<T> T objectFromJson(InputStream in, Class<T> clz) {
        try {
            JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
            T object = sGson.fromJson(reader, clz);
            reader.close();
            return object;
        } catch (UnsupportedEncodingException e) {
            logger.error(e.getMessage(),e.getCause());
        } catch (IOException e) {
            logger.error(e.getMessage(), e.getCause());
        }

        return null;
    }


    /**
     * 用来解析将list的json格式数据反转成object
     * @param listJson
     * @return
     */
    public static List<MsgType> praseListFromJson(List listJson){
        List<MsgType> msgTypeList = new ArrayList<MsgType>();
        for (Object object : listJson) {
            try {
                Class clazz = Class.forName("com.pingba.entity.msg.MsgType");
                MsgType msgType = null;
                msgType = (MsgType) JsonHelp.objectFromJson(object.toString(), clazz);
                msgTypeList.add(msgType);
            } catch (ClassNotFoundException e) {
                logger.error(e.getMessage(), e.getCause());
            }
        }
        return msgTypeList;
    }

    /**
     * 客户端拿到服务端返回的json字符串直接转就可以
     * List中map的具体类型
     *   key         value
     *  “msgSend” -> MsgSend
     *  "msgApply" -> List<MsgApply>
     * @param jsonString
     * @return
     */
    public static List<Map<String, Object>> praseTaskDataStructFromJson(String jsonString) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        try {
            Class mapClass = Class.forName("java.util.HashMap");
            Map map = null;
            map = (Map) JsonHelp.objectFromJson(jsonString, mapClass);
            System.out.println("map1's size is: " + map.size());
            String msgStr = (String) map.get("msg");
            Map map2 = null;
            map2 = (Map) JsonHelp.objectFromJson(msgStr, mapClass);
            System.out.println("map2's size is: " + map2.size());
            for (Object s : map2.values()) {

                Map<String, Object> tempMap = new HashMap<String, Object>();
                resultList.add(tempMap);
                Map msgSendDetailMap = (Map) ((Map) s).get("msgSend");
                MsgSend msgSend = new MsgSend();
                for (Object key : msgSendDetailMap.keySet()) {
                    BeanHelper.setValue(msgSend, (String) key, msgSendDetailMap.get(key));
                }
                tempMap.put("msgSend", msgSend);
                List<MsgApply> applyList = new ArrayList<MsgApply>();
                tempMap.put("msgApply", applyList);
                List<Map> msgApplyDetailMapList = (List<Map>) ((Map) s).get("msgApply");
                for (Map m : msgApplyDetailMapList) {
                    MsgApply apply = new MsgApply();
                    for (Object key : m.keySet()) {
                        BeanHelper.setValue(apply, (String) key, m.get(key));
                    }
                    applyList.add(apply);
                }
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(resultList);
        return resultList;
    }


    public static<T> List<T> praseListFromJson(String jsonString, Class<T> clz) {
        List<T> result = new ArrayList<T>();
        Class mapClass = null;
        try {
            mapClass = Class.forName("java.util.HashMap");
            Map map =  (Map) JsonHelp.objectFromJson(jsonString, mapClass);
            String msgStr = (String) map.get("msg");
            //sGson = new Gson();
            result= sGson.fromJson(msgStr, new TypeToken<List<T>>() {
            }.getType());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }




    /**
     * 客户端拿到服务端返回的json字符串直接转就可以
     * @param jsonString
     * @return
     */
    public static List<MsgSubscribe> praseMsgSubscribeListFromJson(String jsonString) {
        List<MsgSubscribe> result = new ArrayList<MsgSubscribe>();
        Class mapClass = null;
        try {
            mapClass = Class.forName("java.util.HashMap");
            Map map =  (Map) JsonHelp.objectFromJson(jsonString, mapClass);
            String msgStr = (String) map.get("msg");
            //sGson = new Gson();
            result= sGson.fromJson(msgStr, new TypeToken<List<MsgSubscribe>>() {
            }.getType());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        return result;
    }

    public static void main(String args[]) {
//        String jsonStr = "{\"result\":true,\"msg\":[{\"sid\":8837,\"userId\":3,\"longitude\":122.16421,\"latitude\":29.997753,\"content\":\"噢噢噢哦哦陌陌\",\"imgUrl1\":\"diuse-studio.oss-cn-shanghai.aliyuncs.com/20151120230230.jpg\",\"haveResponse\":false,\"readed\":false,\"publishTime\":1448031751248,\"expireTime\":1449031751248,\"typeId\":0}]}";
//        praseTaskDataStructFromJson(jsonStr);
    }
}
